
<template>
    <base-node type="output_to_client" :config="props.data" :id="props.id" ref="baseNode">

        <template #default>
            <div>
                <div class="mt-8 mb-8 fx fx-m_between">
                    <label>是否将AI回答保存到数据库</label>
                    <n-switch v-model:value="props.data.outputToClientConfig.persistDb"/>
                </div>
            </div>
            <n-form-item label="内容来源">
                <n-select placeholder="请选择内容来源" clearable v-model:value="props.data.outputToClientConfig.inputField"
                          :options="prevOutputFieldOptions"></n-select>
            </n-form-item>
            <div v-if="props.data.outputToClientConfig.inputField === 'jb_custom'" @mousedown.stop @wheel.stop>
                <div class="flex justify-between mb-1.5">
                    <label>自定义内容</label>
                    <n-popselect
                        v-model:value="insertValue"
                        :options="insertQuestionOptions"
                        size="medium"
                        scrollable
                    >
                        <n-button strong secondary type="success" size="tiny">
                            <jb-icon :local="true" icon="jam:plus-circle"></jb-icon>
                            插入变量
                        </n-button>
                    </n-popselect>
                </div>
                <textarea v-model="props.data.outputToClientConfig.inputTpl" type="textarea" ref="textarea"
                          placeholder="请输入自定义内容，可以通过插入变量动态生成内容" :rows="8"
                ></textarea>
            </div>
        </template>
    </base-node>
</template>

<script setup>
import {
    useVueFlow
} from '@vue-flow/core'
import {
    watch,  ref, nextTick,  computed
} from "vue";
import BaseNode from '@/views/app/chain/nodes/BaseNode.vue'


const props = defineProps(['id', 'data'])
const flow = useVueFlow();

const baseNode = ref(null);

/** 获取所有前置节点的输出字段，并生成下拉选项 */
const prevOutputFieldOptions = computed(() => {
    if (baseNode.value) {
        return [...baseNode.value.prevOutputFieldOptions, {
            label: "自定义内容",
            value: "jb_custom"
        }]
    } else {
        return [{
            label: "自定义内容",
            value: "jb_custom"
        }]
    }
});



//监听prevOutputFieldOptions
watch(() => prevOutputFieldOptions.value, (newV) => {
    //如果节点初始化完成后，并且某次数组变动后不包含当前值，则清空input的值
    if (baseNode.value?.initDone && newV && !newV.find(v => v.value == props.data.outputToClientConfig.inputField)) {
        props.data.outputToClientConfig.inputField = null;
        //清空输入框
    }
})
flow.onEdgesChange(events => {
    console.debug("intention init", events)
    if (events.some(item => item.type === 'remove' || item.type === 'add')) {
        prevOutputFieldOptions.value = [];
        insertQuestionOptions.value = []
    }
})




/** 获取所有前置节点的输出字段，并生成下拉选项 */

/**动态插入变量-----------------------------*/
//变量数组
const insertQuestionOptions = computed(() => {
    return baseNode.value ? baseNode.value.prevOutputFieldOptions : [];
});
const textarea = ref(null);
const insertValue = ref('')

//选中值,就在光标的指定位置插入值
watch(() => insertValue.value, (newV) => {
    if (newV != "") {
        insertText('${' + newV + '}');
    }
    insertValue.value = '';
})
// 在指定位置插入变量
const insertText = (insertText) => {
    // 确保textarea元素存在
    if (!textarea.value) return;

    // 初始化inputTpl，防止null或undefined的情况
    if (!props.data.outputToClientConfig.inputTpl) {
        props.data.outputToClientConfig.inputTpl = '';
    }

    // 获取光标起始位置和结束位置
    const startPos = textarea.value.selectionStart;
    const endPos = textarea.value.selectionEnd;

    // 插入文本到光标位置后
    const beforeText = props.data.outputToClientConfig.inputTpl.substring(0, startPos);
    const afterText = props.data.outputToClientConfig.inputTpl.substring(endPos, props.data.outputToClientConfig.inputTpl.length);

    // 更新textarea的值
    props.data.outputToClientConfig.inputTpl = beforeText + insertText + afterText;

    // 更新光标位置
    nextTick(() => {
        textarea.value.focus();
        textarea.value.setSelectionRange(startPos + insertText.length, startPos + insertText.length);
    });
};
/**动态插入变量-----------------------------*/


</script>


<style scoped>



label {
    margin-bottom: 8px;
}

label:not(:first-child) {
    margin-top: 16px;
}

textarea {
    width: 100%;
    border-radius: 3px;
    border: 1px solid #bfbfc2;
    padding: 5px;
    /* scrollbar-width: none; 控制滚动条的宽度：auto | thin | none */
}

textarea:focus {
    border: 1px solid #18a058 !important;
    outline: none;
}

</style>
